package com.kkd.kkdapp.fragment;

import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.CreditParticularsActivity;
import com.kkd.kkdapp.activity.ParticularsActivity;
import com.kkd.kkdapp.activity.RepaymentDetailActivity;
import com.kkd.kkdapp.activity.TenderDetailActivity;
import com.kkd.kkdapp.android_async_http.AsyncHttpResponseHandler;
import com.kkd.kkdapp.base.BaseFragment;
import com.kkd.kkdapp.base.MyBaseAdapter;
import com.kkd.kkdapp.http.entity.TenderDetail;
import com.kkd.kkdapp.http.entity.TenderDetailData;
import com.kkd.kkdapp.http.entity.TenderDetailMapList;
import com.kkd.kkdapp.http.manager.HttpCallBack;

import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.Time_Date;

import com.kkd.kkdapp.view.KkdXlistView;
import com.kkd.kkdapp.view.RoundProgressBar;
import com.kkd.kkdapp.view.KkdXlistView.KKDScrollListener;

public class TenderDetailFragment extends BaseFragment implements
		KKDScrollListener {

	private ListAdapter mAdapter;
	private String status;
	private static String toMidFlag = "";
	View noContent;
	private long pageNO = 1;
	private long pageSize = 10;
	private KkdXlistView mXListView;
	private List<TenderDetailMapList> mapList = null;
	private long pageCount;
	private ImageView mNullImg;
	private TextView mNullTv;
	private boolean REFRESHFLAG = true;
	private TenderDetailActivity mTenderDetailActivity;
	private ListView mListView;

	public static TenderDetailFragment newInstance(String status) {
		TenderDetailFragment fragment = new TenderDetailFragment();
		Bundle mBundle = new Bundle();
		mBundle.putString("status", status);
		fragment.setArguments(mBundle);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mTenderDetailActivity = (TenderDetailActivity) activity;
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_tender_detail, null);
		status = getArguments().getString("status");
		toMidFlag = getActivity().getIntent().getStringExtra("toMidFlag");
		initUI(view);
		return view;
	}

	protected void initUI(View view) {
		mXListView = (KkdXlistView) view.findViewById(R.id.manage_lv);
		mNullImg = (ImageView) view.findViewById(R.id.id_no_content);
		mNullTv = (TextView) view.findViewById(R.id.id_no_content_text);

		mXListView.setKKDScrollListener(this);
		mListView = mXListView.mListView;
		mListView.setDividerHeight(0);
		mAdapter = new ListAdapter(getActivity(), this.status);
		mListView.setAdapter(mAdapter);
		mXListView.startRefresh();
		LogUtil.e("TAG", "A");
		if (AppUtil.isConnect(getActivity())) {
			pageNO = 1;
			// mXListView.setPullLoadEnable(true);
			requestTenderDetail(status);
			if (mapList == null) {
				// mNullImg.setVisibility(View.VISIBLE);
				// mNullTv.setVisibility(View.VISIBLE);
				mNullImg.setImageResource(R.drawable.img_null);
			} else {
				mNullImg.setVisibility(View.GONE);
				mNullTv.setVisibility(View.GONE);
			}
		} else {
			// mXListView.setPullLoadEnable(false);
			mNullImg.setVisibility(View.VISIBLE);
			mNullTv.setVisibility(View.VISIBLE);
			mNullTv.setText("网络连接失败，请检查网络！");
			mNullImg.setImageResource(R.drawable.img_null);
			mXListView.stopRefresh();
		}
	}

	public void mOnResume() {
		if (AppUtil.isConnect(getActivity())) {
			// mXListView.setPullLoadEnable(true);
			requestTenderDetail(status);
			if (mapList == null) {
				mNullImg.setVisibility(View.VISIBLE);
				mNullTv.setVisibility(View.VISIBLE);
				mNullImg.setImageResource(R.drawable.img_null);
			} else {
				mNullImg.setVisibility(View.GONE);
				mNullTv.setVisibility(View.GONE);
			}
		} else {
			// mXListView.setPullLoadEnable(false);
			mNullImg.setVisibility(View.VISIBLE);
			mNullTv.setVisibility(View.VISIBLE);
			mNullTv.setText("网络连接失败，请检查网络！");
			mNullImg.setImageResource(R.drawable.img_null);
			mXListView.stopRefresh();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.e("TAG", "C");
	}


	Handler handler = new Handler();

	/**
	 * 请求接口
	 */
	public void requestTenderDetail(String bidStatus) {

		KkdHttpMagager.getInstance().getTenderDetailManager(
				bidStatus, pageNO, pageSize, TenderDetailData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						TenderDetailData data = (TenderDetailData) responseBody;
						long PageSize = data.getPageSize();
						long totalCount = data.getTotalCount();
						LogUtil.e("PageSize", "" + PageSize);
						LogUtil.e("totalCount", "" + totalCount);
						if (totalCount % PageSize != 0) {
							pageCount = (totalCount / PageSize) + 1;
						} else {
							pageCount = (totalCount / PageSize);
						}
						LogUtil.e("pageCount", "" + pageCount);
						if (pageNO > pageCount) {
							mXListView.stopLoadMore(-1);
							if (REFRESHFLAG) {
								mXListView.stopLoadMore(1);
							}
						} else {
							mapList = data.getMapList();
							mAdapter.update();
							mXListView.setNoMore(false);
							mAdapter.appendData(mapList, pageNO == 1);
							mAdapter.notifyDataSetChanged();
							if (mapList.size() < pageSize) {
								mXListView.stopLoadMore(1);
							} else {
								mXListView.stopLoadMore(0);
							}
							mXListView.stopRefresh();
							Time_Date time_Date = new Time_Date();
							String time = time_Date.get_Year_Day();
							mXListView.setRefreshTime(time);
						}
						mXListView.stopRefresh();
						Time_Date time_Date = new Time_Date();
						String time = time_Date.get_Year_Day();
						mXListView.setRefreshTime(time);
						if (REFRESHFLAG) {
							if (mapList == null) {
								mNullImg.setVisibility(View.VISIBLE);
								mNullTv.setVisibility(View.VISIBLE);
								if (status.equals("5004")) {
									mNullTv.setText("暂无还款记录，赶紧去投标吧~");
									mNullImg.setImageResource(R.drawable.img_null);
								} else if (status.equals("5005")) {
									mNullImg.setImageResource(R.drawable.img_null);
									mNullTv.setText("暂无已还款记录，赶紧去投标吧~");
								}
								// mXListView.setPullLoadEnable(false);
							} else {
								// mXListView.setPullLoadEnable(true);
								mNullImg.setVisibility(View.GONE);
								mNullTv.setVisibility(View.GONE);
							}
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(mTenderDetailActivity, desc);
						mXListView.stopLoadMore(1);
						mXListView.stopRefresh();
					}
				});
	}

	private static class ListAdapter extends MyBaseAdapter<TenderDetailMapList> {

		LayoutInflater mInflater;

		String bidStatus;
		// String poiId;
		// String bidId;
		private TenderDetailMapList data;

		public ListAdapter(Context context, String bidStatus) {
			super(context);
			mInflater = LayoutInflater.from(context);
			this.bidStatus = bidStatus;
		}

		@Override
		public View getMyView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.tender_detail_list_item, null);
				holder = new ViewHolder();
				holder.mButton = (Button) convertView
						.findViewById(R.id.return_detail);
				holder.progressBar1 = (RoundProgressBar) convertView
						.findViewById(R.id.progressBar1);
				holder.mTop = (RelativeLayout) convertView
						.findViewById(R.id.title_area);

				holder.title = (TextView) convertView
						.findViewById(R.id.item_title);
				holder.poiAmount = (TextView) convertView
						.findViewById(R.id.poi_amount);

				holder.poiDate = (TextView) convertView
						.findViewById(R.id.poi_date);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			data = myList.get(position);
			String bidAmount = data.getBidAmount();
			String bidFreeAmount = data.getBidFreeAmount();
			LogUtil.e("bidAmount", bidAmount);
			LogUtil.e("bidFreeAmount", bidFreeAmount);
			double interest = (Double.parseDouble(bidAmount) - Double
					.parseDouble(bidFreeAmount))
					/ Double.parseDouble(bidAmount);
			holder.progressBar1.setTextSize(SystemUtils.dip2px(context, 10));
			holder.progressBar1.setRoundWidth(SystemUtils.dip2px(context, 5));
			LogUtil.e("progressBar1", "" + data.getBidProgress());
			holder.progressBar1.setPropress(data.getBidProgress() + "%");
			LogUtil.e("interest", "" + interest);
			int interest1 = (int) (interest * 100);
			LogUtil.e("interest", "" + interest1);
			if (Double.parseDouble(data.getBidProgress()) < 1) {
				holder.progressBar1.setProgress(1);
			} else if (Double.parseDouble(data.getBidProgress()) > 1) {
				holder.progressBar1.setProgress(interest1);
			}
			holder.poiDate.setText((data.getPoiDate()).replaceAll("-", "/"));
			holder.poiAmount.setText(data.getPoiAmount());
			holder.title.setText(data.getBidTitle());
			if ("5002".equals(bidStatus)) {
				holder.mButton.setVisibility(View.GONE);
				holder.progressBar1.setVisibility(View.VISIBLE);

			}

			holder.mTop.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent;
					if (myList.get(position).getBidProductType() == 3) {
						intent = new Intent(context,
								CreditParticularsActivity.class);
						intent.putExtra("bidId", myList.get(position)
								.getBidId());
						context.startActivity(intent);
					} else {
						intent = new Intent(context, ParticularsActivity.class);
						intent.putExtra("toMidFlag", toMidFlag);
						intent.putExtra("bidId", myList.get(position)
								.getBidId());
						context.startActivity(intent);
					}

				}
			});
			if (!"5002".equals(bidStatus) && holder != null) {
				holder.mButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context,
								RepaymentDetailActivity.class);
						intent.putExtra("poiId", myList.get(position)
								.getPoiId());
						context.startActivity(intent);
					}
				});
			}
			return convertView;
		}

		private class ViewHolder {
			public TextView title;
			public Button mButton;
			public RelativeLayout mTop;
			public RoundProgressBar progressBar1;
			public TextView poiAmount;
			public TextView poiDate;
		}

	}

	@Override
	public void onRefresh() {
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				pageNO = 1;
				requestTenderDetail(status);
				REFRESHFLAG = true;
			}
		}, 1000);
	}

	@Override
	public void onLoadMore() {
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				LogUtil.e("加载更多", "");
				pageNO++;
				requestTenderDetail(status);
				REFRESHFLAG = false;
			}
		}, 1000);
	}

}
